﻿using System.Diagnostics;
using System.IO;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using HandyControl.Controls;
using Om.Core.Extension;
using Om.Core.Singleton;

namespace OptoMeasure.Views;

public partial class CaptureViewModel : ObservableObject
{
    [ObservableProperty] private bool _isCapturing;
    [ObservableProperty] private double _intervalSeconds = 5;

    private Timer _timer;


    [RelayCommand]
    private async Task StartCapture()
    {
        //if (DevicesManager.Instance.Signal?.Client?.Online != true)
        //    return;
        //var ms = (int)(IntervalSeconds * 1000);
        //var res = await DevicesManager.Instance.Signal.StartSendSignal(ms);
        //if (!res)
        //{
        //    MessageBox.Error("操作失败");
        //    return;
        //}

        _timer = new Timer(TimerCallBack, null, 0, (int)(IntervalSeconds * 1000));
        IsCapturing = true;
    }
    async void TimerCallBack(object state)
    {

        await Capture();
    }

    [RelayCommand]
    private async Task StopCapture()
    {
        //if (DevicesManager.Instance.Signal?.Client?.Online != true)
        //    return;
        //var res = await DevicesManager.Instance.Signal.StartSendSignal(0);
        //if (!res)
        //{
        //    MessageBox.Error("操作失败");
        //    return;
        //}

        _timer.Dispose();
        IsCapturing = false;
    }

    [RelayCommand]
    private void OpenFolder()
    {
        var path = CaptureHelper.GetFolderPath();
        Process.Start("explorer.exe", path);
    }

    [RelayCommand]
    private async Task Capture()
    {
        var cameras = DevicesManager.Instance.GetBaseCameras();
        foreach (var kv in cameras)
        {
            var cam = kv.Value;
            if(!cam.IsConnected) continue;

            var path = CaptureHelper.GetFileFullPath(kv.Key);
            cam.Capture(path);
        }
    }
}